package com.ciwong.epaper.modules.epaper.ui;


import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.HideDownloadDialogBean;
import com.ciwong.epaper.common.guidedialog.ChooseReadDialog;
import com.ciwong.epaper.modules.epaper.adapter.ContentListAdapter;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.MultipleServicesDialog;
import com.ciwong.epaper.modules.me.bean.CheckValidBean;
import com.ciwong.epaper.modules.me.bean.ServiceDetail;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.ServicePermissionJudgeUtil;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.widget.ItemNoMoreBottom;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.bean.Main;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseIntentFlag;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.TitleBar;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 书籍详情--书籍内容页面
 * Created by Administrator on 2016/11/23.
 */
public class NewContentActivity extends BaseActivity {

    public static final int REQ_CODE_EXPIRE_TO_BUY_SERVICE = 104;// 已过期的服务去购买


    private DownLoadInfo downLoadInfo;

    private ListView list_view;
    private ContentListAdapter mContentListAdapter;
    private int mServiceId;

    private EpaperInfo mEpaperInfo;

    private Module mModule;

    private String mJsonVersion;

    private ServiceDetail mServiceDetail;

    private EApplication eApplication;

    /**
     * 模块内容
     */
    private List<ModuleContent> mResourceList = new ArrayList<>();


    private ChooseReadDialog dialog;

    private Map<Integer, Module> versionIdMapMo = new HashMap<Integer, Module>();
    /**
     * 扫一扫数据所属的服务列表
     */
    private List<EpaperInfo.Server> mEpaperServerList;


    private List<Module> mModuleList = new ArrayList<>();

    private TitleBar titleBar;


    @Override
    protected int setView() {

        return R.layout.activity_new_content;
    }

    @Override
    protected void findViews() {
        titleBar = (TitleBar) findViewById(R.id.activity_base_titlebar);
        list_view = (ListView) findViewById(R.id.list_view);

    }

    @Override
    protected void initEvent() {
        list_view.setOnItemClickListener(onItemClickListener);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void init() {
        downLoadInfo = (DownLoadInfo) getIntent()
                .getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
        mEpaperInfo = (EpaperInfo) getIntent().getSerializableExtra(BaseIntentFlag.INTENT_FLAG_OBJ);
        mServiceId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
        mEpaperServerList = (List<EpaperInfo.Server>) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);


        titleBar.setTitle(downLoadInfo.getChapterName());
        eApplication = EApplication.getInstance();
    }

    @Override
    protected void loadData() {
        String path = ESystem.getPackagesMainJsonPath(downLoadInfo.getBookId(),
                downLoadInfo.getChapterId());

        EpaperDao.getInstance().getSerializableObjects(path, Main.class,
                new BaseExtCallBack(NewContentActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    public void failed(Object data) {
                        CWToast.makeText(NewContentActivity.this, (int) data,
                                Toast.LENGTH_LONG, true)
                                .setToastType(CWToast.TOAST_TYPE_ERROR).show();
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void success(Object data) {
                        Main main = (Main) data;
                        getCatalogueFile(main.getCatalogueFile(),
                                main.getJsonVersion());

                        mJsonVersion = main.getJsonVersion();

                    }
                });
        if(!NetworkUtils.isOnline()){
            ToastUtil.INSTANCE.toastCenterNoNetError();
        }

    }


    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int modulePosition, long id) {

            if (!DoubleClickCheckUtils.vertifyDuration()) {
                return;
            }
            if (modulePosition < mResourceList.size()) {
                final ModuleContent moduleContent = mResourceList.get(modulePosition);
                mModule = versionIdMapMo.get(modulePosition);
                //要区分是从扫一扫进来还是书桌进来的
                //如果最后都未空说明没购买没试用
                mServiceDetail = null;

                int position = 0;
                List<ModuleContent> moduleContentList = mModule.getResourceList();
                for (int i = 0; i < moduleContentList.size(); i++) {
                    //versionId parentVersionId resourceType 确定唯一性
                    if (moduleContent.getVersionId().equals(moduleContentList.get(i).getVersionId()) && moduleContent.getParentVersionId().equals(moduleContentList.get(i).getParentVersionId())) {
                        position = i;
                        break;
                    }
                }
                final int moduleId;
                if (downLoadInfo != null && downLoadInfo.getType() == 1) {
                    moduleId = Integer.parseInt(downLoadInfo.getModuleId());
                } else {
                    moduleId = mModule.getModuleInfo().getModuleId();
                }


//                Log.d("callback", "########isCallBack########" + isCallBack);
//                if (!isCallBack) {
////                    showCricleProgress();
//                    return;
//                }
//
//                if (moduleId != ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN_NEW && moduleId != ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN) {
//                    isCallBack = false;
//                }


                showDownloadProgress();

                ServicePermissionJudgeUtil.servicePermissionFilter2(NewContentActivity.this, downLoadInfo, mModule, mEpaperInfo, moduleContent, mServiceId, mEpaperServerList, position, false,false, new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
//                        mHandler.sendEmptyMessageDelayed(0, 2000);
                    }

                    @Override
                    public void failed(Object data) {
//                        mHandler.sendEmptyMessageDelayed(0, 2000);
                    }

                    @Override
                    public void success(Object data) {
                        final CheckValidBean checkValidBean = (CheckValidBean) data;
//                        mHandler.sendEmptyMessageDelayed(0, 2000);
                        //没有权限
                        //没有权限
                        if (mServiceId == -1 && null != checkValidBean && checkValidBean.isValid == 0) {
                            //扫描特有 逻辑
                            MultipleServicesDialog.OnServicesItemClick onServicesItemClick = new MultipleServicesDialog.OnServicesItemClick() {
                                @Override
                                public void onServicesItemClick(int position) {
                                    MeJumpManager.jumpBuyService(NewContentActivity.this, R.string.go_back, checkValidBean.services.get(position).id, -1,  RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, checkValidBean.msg);
                                }
                            };
                            MultipleServicesDialog multipleServicesDialog = new MultipleServicesDialog(NewContentActivity.this, checkValidBean.services, onServicesItemClick);
                            try {//有可能已经退出扫码界面，才请求到权限。防止崩溃。

                                if (checkValidBean.services.size() == 1) {
                                    MeJumpManager.jumpBuyService(NewContentActivity.this, R.string.go_back, checkValidBean.services.get(0).id, -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, checkValidBean.msg);
                                } else {
                                    multipleServicesDialog.show();
                                    multipleServicesDialog.setTitle(checkValidBean.msg);
                                }
                            } catch (Exception e) {

                            } finally {

                            }

                        }

                    }
                });
            }


        }
    };


    /**
     * 获取目录内容信息
     *
     * @param path        目录内容信息地址
     * @param jsonVersion
     */
    private void getCatalogueFile(String path, final String jsonVersion) {
        path = ESystem.getPackagesPath(NewContentActivity.this) + File.separator + path;
        Type responseType = new TypeToken<List<Module>>() {
        }.getType();
        EpaperDao.getInstance().getSerializableObjects(path, responseType,
                new BaseExtCallBack(NewContentActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                    @Override
                    public void failed(Object data) {
                        //showToastError(String.valueOf(data));
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void success(Object data) {
                        mModuleList = (List<Module>) data;
                        if (mModuleList == null) {
                            return;
                        }

                        for (Module module : mModuleList) {
                            List<ModuleContent> moduleContentList = module.getResourceList();
                            if (null != moduleContentList && moduleContentList.size() > 0) {
                                for (int i = 0; i < moduleContentList.size(); i++) {
                                    versionIdMapMo.put(mResourceList.size(), module);
                                    ModuleContent moduleContent = moduleContentList.get(i);
                                    if (TextUtils.isEmpty(moduleContent.isDeleted) || !moduleContent.isDeleted.equals("1")) {//单元没有被删除
                                        mResourceList.add(moduleContentList.get(i));
                                    }
                                }
                            }
                        }

                        mContentListAdapter = new ContentListAdapter(NewContentActivity.this, mResourceList, versionIdMapMo);
                        list_view.setAdapter(mContentListAdapter);

                        if (null == mResourceList || mResourceList.size() == 0) {
                            ItemNoMoreBottom itemNoMoreBottom = new ItemNoMoreBottom(NewContentActivity.this);
                            list_view.addFooterView(itemNoMoreBottom);
                        }

                    }
                });
    }

    //隐藏加载框
    public void onEventMainThread(HideDownloadDialogBean hideDownloadDialogBean){
        hideDownloadProgress();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }
}
